import time
import torch
import random
import numpy as np
from data import create_dataset
from models import create_model
from util.visualizer import Visualizer

from configs import default_argument_parser
from data.get_util import get_logger
from util.evaluation import evaluate_2D
import os

os.environ['CUDA_VISIBLE_DEVICES'] = '1'

if __name__ == '__main__':
    config = default_argument_parser()
    logger = get_logger('Config')
    logger.info(config)

    manual_seed = config.get('manual_seed', None)
    if manual_seed is not None:
        logger.info(f'Seed the RNG for all devices with {manual_seed}')
        logger.warning('Using CuDNN deterministic setting. This may slow down the training!')
        random.seed(manual_seed)
        torch.manual_seed(manual_seed)
        # see https://pytorch.org/docs/stable/notes/randomness.html
        torch.backends.cudnn.deterministic = True

    dataset = create_dataset(config.loaders, phase='test')  # create a dataset given opt.dataset_mode and other options
    val_dataset = create_dataset(config.loaders, phase='val')
    dataset_size = len(dataset)    # get the number of images in the dataset.
    print('The number of test images = %d' % dataset_size)

    model = create_model(config)      # create a model given opt.model and other options

    model.setupTest(config)               # regular setup: load and print networks; create schedulers
    visualizer = Visualizer(config)   # create a visualizer that display/save images and plots
    total_iters = 0                # the total number of training iterations
    ssim_max = 0

    # outer loop for different epochs; we save the model by <epoch_count>, <epoch_count>+<save_latest_freq>
    epoch_start_time = time.time()  # timer for entire epoch
    iter_data_time = time.time()    # timer for data loading per iteration
    epoch_iter = 0                  # the number of training iterations in current epoch, reset to 0 every epoch
    visualizer.reset()              # reset the visualizer: make sure it saves the results to HTML at least once every epoch
    # model.update_learning_rate()    # update learning rates in the beginning of every epoch.
    for i, data in enumerate(dataset):  # inner loop within one epoch
        iter_start_time = time.time()  # timer for computation per iteration
        if total_iters % config.trainer.print_freq == 0:
            t_data = iter_start_time - iter_data_time

        total_iters += config.loaders.batch_size
        epoch_iter += config.loaders.batch_size
        model.set_input(data)         # unpack data from dataset and apply preprocessing
        # model.optimize_parameters(cur_nimg=total_iters)   # calculate loss functions, get gradients, update network weights
        model.test()
        # if 0 == 0:   # display images on visdom and save images to a HTML file

        model.compute_visuals()
        visualizer.display_test_results(model.get_current_visuals(), i, True)

        # if 0 == 0:    # print training losses and save logging information to the disk
        #     losses = model.get_current_losses()
        #     t_comp = (time.time() - iter_start_time) / config.loaders.batch_size
        #     visualizer.print_current_losses(0, epoch_iter, losses, t_comp, t_data)
        #     if config.display.display_id > 0:
        #         visualizer.plot_current_losses(0, float(epoch_iter) / dataset_size, losses)



